package cn.kooki.app.duobao.ui.Activity.User;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.ShipAddressItem;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.address.AddressItem;
import cn.kooki.app.duobao.data.Bean.User.address.AddressResponse;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.CityListChangeEvent;
import cn.kooki.app.duobao.ui.Adapter.AddressSpinnerAdapter;
import cn.kooki.app.duobao.ui.widget.ClearEditText;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/14.
 */
public class AddShipAddressActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.ship_address_edit_name)
    ClearEditText shipAddressEditName;
    @Bind(R.id.ship_address_edit_mobile)
    ClearEditText shipAddressEditMobile;
    @Bind(R.id.ship_address_edit_aname)
    Spinner shipAddressEditAname;
    @Bind(R.id.ship_address_edit_aname_error)
    TextView shipAddressEditAnameError;
    @Bind(R.id.ship_address_edit_bname)
    Spinner shipAddressEditBname;
    @Bind(R.id.ship_address_edit_bname_error)
    TextView shipAddressEditBnameError;
    @Bind(R.id.ship_address_edit_cname)
    Spinner shipAddressEditCname;
    @Bind(R.id.ship_address_edit_cname_error)
    TextView shipAddressEditCnameError;
    @Bind(R.id.ship_address_edit_detail)
    ClearEditText shipAddressEditDetail;
    @Bind(R.id.ship_address_edit_del)
    RelativeLayout shipAddressEditDel;
    @Bind(R.id.switch_is_moren)
    SwitchCompat switchIsMoren;
    private ArrayList<AddressItem> pros = new ArrayList<>();
    private ArrayList<AddressItem> citys = new ArrayList<>();
    private ArrayList<AddressItem> dists = new ArrayList<>();
    private AddressItem selectitem;
    private AddressSpinnerAdapter spinnerAdapter;
    private AddressSpinnerAdapter cspinnerAdapter;
    private AddressSpinnerAdapter dspinnerAdapter;

    private final static int TYPE_PRO = 0;
    private final static int TYPE_CITY = 1;
    private final static int TYPE_DIST = 2;

    private AddressItem proitem;
    private AddressItem citem;
    private AddressItem ditem;
    private UserInfo userinfo;
    private ShipAddressItem item;
    private boolean ischange = false;


    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_ship_address_edit);
        ButterKnife.bind(this);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void afterView() {
        userinfo = SharePreferencesUtils.getUserinfo(this);
        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkback()) return;
                finish();
            }
        });
        actionEdit.setText(R.string.save);

        actionEdit.setTextColor(getResources().getColor(R.color.blue));
        actionEdit.setOnClickListener(this);
        actionEdit.setVisibility(View.VISIBLE);

        item = getIntent().getParcelableExtra("item");
        if (item != null) {
            setTitle(R.string.title_ship_address_edit);
        } else {
            setTitle(R.string.title_ship_address_add);
        }
        predata();
        spinnerAdapter = new AddressSpinnerAdapter(this, pros);
        cspinnerAdapter = new AddressSpinnerAdapter(this, citys);
        dspinnerAdapter = new AddressSpinnerAdapter(this, dists);
        shipAddressEditAname.setAdapter(spinnerAdapter);
        shipAddressEditAname.setPrompt("请选择省份");
        shipAddressEditAname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                ischange = true;

                if (position == 0) {
                    return;
                } else {
                    proitem = pros.get(position);
                    shipAddressEditAnameError.setError(null);
                    getcitylist(TYPE_CITY, proitem.getId());
                    shipAddressEditBname.setSelection(0, true);
                    shipAddressEditCname.setSelection(0, true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        shipAddressEditBname.setAdapter(cspinnerAdapter);
        shipAddressEditBname.setPrompt("请选择城市");

        shipAddressEditBname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ischange = true;

                if (position == 0) {
                    return;
                } else {
                    citem = citys.get(position);
                    shipAddressEditBnameError.setError(null);
                    getcitylist(TYPE_DIST, citem.getId());
                    shipAddressEditCname.setSelection(0, true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        shipAddressEditCname.setAdapter(dspinnerAdapter);
        shipAddressEditCname.setPrompt("请选择地区");
        shipAddressEditCname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ischange = true;

                if (position == 0) {
                    return;
                } else {
                    ditem = dists.get(position);
                    shipAddressEditCnameError.setError(null);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }

    @Override
    public void onBackPressed() {

        if (checkback()) return;
        super.onBackPressed();
    }

    private boolean checkback() {
        if (item != null) {
            if (checkchange() || ischange) {

                new AlertDialog.Builder(this).setCancelable(false).
                        setMessage("您已修改但未保存，真的要返回么？").
                        setPositiveButton("取消", null).
                        setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
                return true;
            }
        }
        return false;
    }

    private boolean checkchange() {
        if (!item.shouhuoren.equals(shipAddressEditName.getText().toString())) {
            return true;
        }
        if (!item.shouji.equals(shipAddressEditMobile.getText().toString())) {
            return true;
        }
        if (!item.jiedao.equals(shipAddressEditDetail.getText().toString())) {
            return true;
        }
        return false;
    }

    private void preItemList(final int type, String pid) {
        MainFactory.getApiInstance().listCitys(pid, new Callback<AddressResponse>() {
            @Override
            public void success(AddressResponse baseResponse, Response response) {
                if (type == TYPE_PRO) {
                    pros.addAll(baseResponse.data);
                    spinnerAdapter.notifyDataSetChanged();
                    findidbyItem(type);
                } else if (type == TYPE_CITY) {
                    citys.clear();
                    citys.add(selectitem);
                    citys.addAll(baseResponse.data);
                    cspinnerAdapter.notifyDataSetChanged();
                    findidbyItem(type);
                } else {
                    dists.clear();
                    dists.add(selectitem);
                    dists.addAll(baseResponse.data);
                    dspinnerAdapter.notifyDataSetChanged();
                    findidbyItem(type);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (error.getKind() == RetrofitError.Kind.NETWORK) {
                    showToastMessage(getString(R.string.network_error));
                }
            }
        });
    }

    private void findidbyItem(int type) {
        if (type == TYPE_PRO) {
            for (int i = 0; i < pros.size(); i++) {
                AddressItem addressItem = pros.get(i);
                if (addressItem.getName().equals(item.sheng)) {
                    proitem = addressItem;
                    shipAddressEditAname.setSelection(i);
                    preItemList(TYPE_CITY, proitem.getId());
                    break;
                }
            }
        } else if (type == TYPE_CITY) {
            for (int i = 0; i < citys.size(); i++) {
                AddressItem addressItem = citys.get(i);
                if (addressItem.getName().equals(item.shi)) {
                    citem = addressItem;
                    shipAddressEditBname.setSelection(i);
                    preItemList(TYPE_DIST, citem.getId());
                    break;
                }
            }
        } else {
            for (int i = 0; i < dists.size(); i++) {
                AddressItem addressItem = dists.get(i);
                if (addressItem.getName().equals(item.xian)) {
                    ditem = addressItem;
                    shipAddressEditCname.setSelection(i);
                    break;
                }
            }
        }
    }

    private void getcitylist(final int type, String pid) {
        MainFactory.getApiInstance().listCitys(pid, new Callback<AddressResponse>() {
            @Override
            public void success(AddressResponse baseResponse, Response response) {
                if (type == TYPE_PRO) {
                    pros.addAll(baseResponse.data);
                    spinnerAdapter.notifyDataSetChanged();
                } else if (type == TYPE_CITY) {
                    citys.clear();
                    citys.add(selectitem);
                    citys.addAll(baseResponse.data);
                    cspinnerAdapter.notifyDataSetChanged();
                } else {
                    dists.clear();
                    dists.add(selectitem);
                    dists.addAll(baseResponse.data);
                    dspinnerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (error.getKind() == RetrofitError.Kind.NETWORK) {
                    showToastMessage(getString(R.string.network_error));
                }
            }
        });
    }

    private void predata() {
        selectitem = new AddressItem();
        selectitem.setName("请选择");
        selectitem.setId("-1");
        pros.add(selectitem);
        citys.add(selectitem);
        dists.add(selectitem);

        if (item != null) {
            shipAddressEditName.setText(item.shouhuoren);
            shipAddressEditMobile.setText(item.shouji);
            shipAddressEditDetail.setText(item.jiedao);
            shipAddressEditDel.setVisibility(View.VISIBLE);
            shipAddressEditDel.setOnClickListener(this);
            preItemList(TYPE_PRO, "0");
            switchIsMoren.setChecked(item.moren.equals("Y"));
        } else {
            shipAddressEditDel.setVisibility(View.GONE);
            getcitylist(TYPE_PRO, "0");
        }

    }


    @Override
    public void onClick(View v) {
        if (v == actionEdit) {
            if (checkfrom()) {
                upload();
            }
        }
        if (v == shipAddressEditDel) {

            new AlertDialog.Builder(this).setCancelable(false).setTitle("提示").
                    setMessage("确定删除么？").
                    setPositiveButton("取消", null).
                    setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteAddress();
                        }
                    }).show();
        }
    }

    private void deleteAddress() {
        showLoading("正在删除");
        MainFactory.getApiInstance().deleteAddress(userinfo.getUid(), item.id, new Callback<BaseResponse>() {
            @Override
            public void success(BaseResponse baseResponse, Response response) {
                dismissLoading();
                if (baseResponse.getStatus() == 0) {
                    showToastMessage("保存成功");
                    EventBus.getDefault().post(new CityListChangeEvent());
                    finish();
                } else {
                    showToastMessage(baseResponse.getMsg());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                dismissLoading();
                if (error.getKind() == RetrofitError.Kind.NETWORK) {
                    showToastMessage(getString(R.string.network_error));
                }
            }
        });
    }

    private void upload() {

        showLoading("正在添加");

        HashMap<String, Object> params = new HashMap<>();
        params.put("uname", userinfo.getUid());
        if (item != null) {
            params.put("id", item.id);
        } else {
            params.put("id", "0");
        }
        params.put("sheng", proitem.getName());
        params.put("shi", citem.getName());
        params.put("xian", ditem.getName());
        params.put("shouhuoren", shipAddressEditName.getText().toString());
        params.put("shouji", shipAddressEditMobile.getText().toString());
        params.put("jiedao", shipAddressEditDetail.getText().toString());
        params.put("moren", switchIsMoren.isChecked());
        MainFactory.getApiInstance().addaddress(params,
                new Callback<BaseResponse>() {

                    @Override
                    public void success(BaseResponse baseResponse, Response response) {
                        dismissLoading();
                        if (baseResponse.getStatus() == 0) {
                            showToastMessage("保存成功");
                            EventBus.getDefault().post(new CityListChangeEvent());
                            finish();
                        } else {
                            showToastMessage(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        dismissLoading();
                        if (error.getKind() == RetrofitError.Kind.NETWORK) {
                            showToastMessage(getString(R.string.network_error));
                        }

                    }
                }
        );
    }

    private boolean checkfrom() {
        if (TextUtils.isEmpty(shipAddressEditName.getText().toString())) {
            shipAddressEditName.setError("请输入收货人姓名");
            return false;
        }

        if (!StringUtils.isMobile(shipAddressEditMobile.getText().toString())) {
            shipAddressEditMobile.setError("请输入正确的手机号");
            return false;
        }
        if (proitem == null) {
            shipAddressEditAnameError.setError("");
            return false;
        }
        if (citem == null) {
            shipAddressEditBnameError.setError("");
            return false;
        }
        if (ditem == null) {
            shipAddressEditCnameError.setError("");
            return false;
        }
        if (TextUtils.isEmpty(shipAddressEditDetail.getText().toString())) {
            shipAddressEditDetail.setError("请输入详细地址");
            return false;
        }
        return true;
    }


}
